package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.nursing.vo.ato.IotMsgNotifyData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 *
 * @author tfx
 * @date 2025-06-02
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IoTDAClient client;


    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {

    }

    /**
     * 查询设备数据列表
     *
     * @param device 设备数据
     * @return 设备数据
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return  deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 获取所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从缓存中获取
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        //如果数据为空则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备是否已经存在
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if(count(queryWrapper) > 0){
            throw new BaseException("设备已经存在,请重新输入");
        }
        //检验设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNoId = new LambdaQueryWrapper<>();
        queryWrapperNoId.eq(Device::getIotId, deviceDto.getNodeId());
        if(count(queryWrapperNoId) > 0){
            throw new BaseException("设备标识码已经存在,请重新输入");
        }
        //校验同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> queryWrapperLocation = new LambdaQueryWrapper<>();

        queryWrapperLocation.eq(Device::getLocationType, deviceDto.getLocationType());
        queryWrapperLocation.eq(Device::getProductKey, deviceDto.getProductKey());
        queryWrapperLocation.eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType());
        queryWrapperLocation.eq(Device::getDeviceDescription, deviceDto.getBindingLocation());
        if(count(queryWrapperLocation) > 0){
            throw new BaseException("同一位置只能绑定同一产品,请重新选择");
        }

        //iot中添加设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice body  = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        addDeviceRequest.withBody(body);
        AuthInfo authInfo = new AuthInfo();
        //秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        AddDeviceResponse response;
        try {
            response = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        //设备数据保存到数据库
        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        //秘钥
        device.setSecret(secret);
        //在数据库中新增设备
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("同一个位置不能绑定同类型的产品");
        }
    }

    /**
     * 获取设备信息
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceInfo(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)){
            return null;
        }
        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /**
     * 查询设备最新数据
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        List<DeviceShadowDataVo> voList = new ArrayList<>();
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            //System.out.println(response.toString());
            List<DeviceShadowData> list = response.getShadow();
            for (DeviceShadowData deviceShadowData : list) {
                //上报的数据
                DeviceShadowProperties reported = deviceShadowData.getReported();
                LinkedHashMap<String, Object> propertiesData = (LinkedHashMap) reported.getProperties();
                //上报数据的时间
                String eventTime = reported.getEventTime();
                LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime activeDateTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        //转时区，获取系统中的时区
                        .withZoneSameInstant(ZoneId.systemDefault())
                        .toLocalDateTime();
                //把map中的每个数据转成List
                voList = propertiesData.entrySet().stream().map(entry -> {
                    DeviceShadowDataVo vo = new DeviceShadowDataVo();
                    vo.setEventTime(activeDateTime);
                    vo.setFunctionId(entry.getKey());
                    vo.setValue(entry.getValue().toString());
                    return vo;
                }).collect(Collectors.toList());
            }
        }catch (Exception e){
            log.error("查询设备服务属性失败", e);
            throw new BaseException("查询设备最新数据失败");
        }
        return voList;
    }
    public static void main(String[] args) {
        System.out.println("ZoneId.systemDefault() = " + ZoneId.systemDefault());
    }
}
